module repository.role;

import database.mydb;
import models.role;

/** 
 * 获取角色列表
 * Returns: Role[]
 */
Role[] getAllRoles()
{
    return dbsess.createQuery("FROM Role ORDER BY id").list!Role();
}

/** 
 * 通过角色id获取角色
 * Params:
 *   roleId = long
 * Returns: Role
 */
Role getRoleById(long roleId)
{
    Role role = dbsess.createQuery("FROM Role WHERE id=:roleId")
        .setParameter("roleId", roleId).uniqueResult!Role();

    return role;
}

/** 
 * 通过角色ids获取角色列表
 * Params:
 *   roleIds = long[]
 * Returns: Role[]
 */
Role[] getRolesByIds(long[] roleIds)
{
    Role[] roles = [];
    foreach (long roleId; roleIds)
    {
        Role role = dbsess.createQuery("FROM Role WHERE id=:roleId")
            .setParameter("roleId", roleId).uniqueResult!Role();
        roles ~= role;
    }

    return roles;
}

/** 
 * 添加角色
 * Params:
 *   newRole = Role
 * Returns: bool
 */
bool doAddRole(Role newRole)
{
    auto res = dbsess.save(newRole);
    if (!res.hasValue || res <= 0)
    {
        return false;
    }
    return true;
}

/** 
 * 删除角色
 * Params:
 *   roleId = long
 * Returns: bool
 */
bool deleteRoleById(long roleId)
{
    Role role = dbsess.createQuery("FROM Role WHERE id=:roleId")
        .setParameter("roleId", roleId).uniqueResult!Role();

    if (role is null)
    {
        return false;
    }
    dbsess.remove(role);
    return true;
}

/** 
 * 批量删除
 * Params:
 *   roleIds = long[]
 * Returns: bool
 */
bool deleteRoleByIds(long[] roleIds)
{
    foreach (rid; roleIds)
    {
        Role role = dbsess.createQuery("FROM Role WHERE id=:roleId")
            .setParameter("roleId", rid).uniqueResult!Role();

        if (role is null)
        {
            continue;
        }
        dbsess.remove(role);
    }

    return true;
}

/** 
 * 修改角色
 * Params:
 *   newRole = Role
 * Returns: bool
 */
bool doUpdateRole(long roleId, Role newRole)
{
    Role oldRole = dbsess.createQuery("FROM Role WHERE id=:roleId")
        .setParameter("roleId", roleId).uniqueResult!Role();
    if (oldRole is null)
    {
        return false;
    }
    oldRole.code = newRole.code;
    oldRole.name = newRole.name;
    oldRole.sort = newRole.sort;
    oldRole.status = newRole.status;

    dbsess.update(oldRole);
    return true;
}

/** 
 * 修改角色拥有的菜单
 * Params:
 *   roleId = long
 *   menuIds = long[]
 * Returns: bool
 */
bool doUpdateRoleMenu(long roleId, long[] menuIds)
{
    import repository.menu : getMenuListByIds;

    auto role = getRoleById(roleId);
    if (role is null)
    {
        return false;
    }
    auto menuList = getMenuListByIds(menuIds);
    role.menus = menuList;

    dbsess.update(role);
    return true;
}
